﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Web;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;

namespace SBACN.WebSite
{
	public class Global : System.Web.HttpApplication
	{
		protected void Application_Start(object sender, EventArgs e)
		{

		}

		protected void Session_Start(object sender, EventArgs e)
		{

		}

		protected void Application_BeginRequest(object sender, EventArgs e)
		{
		}

		protected void Application_EndRequest(object sender, EventArgs e)
		{
			SBACNEntities objectContext = CallContext.GetData(typeof(SBACNEntities).FullName) as SBACNEntities;
			if(objectContext != null)
			{
				objectContext.Dispose();
			}
		}

		protected void Application_AuthenticateRequest(object sender, EventArgs e)
		{

		}

		protected void Application_Error(object sender, EventArgs e)
		{
			//SBACNEntities objectContext = CallContext.GetData(typeof(SBACNEntities).FullName) as SBACNEntities;
			//if (objectContext != null)
			//{
			//    objectContext.Dispose();
			//}
			Exception ex = Server.GetLastError();
			if(ex != null)
			{
				if (ex is HttpException)
				{
					HttpException httpEx = ex as HttpException;
					if(httpEx.GetHttpCode() == 403 || httpEx.GetHttpCode() == 404)
					{
						//Response.Redirect("~/Error.aspx");
						//Response.End();
						//Server.Transfer("~/Error.aspx?m=");
						//Server.ClearError();
						return;
					}
				}

				ex = ex.GetBaseException();
				string err = "Error Caught in Application_Error event\n" + "Error in:" + Request.Url.ToString() + "\nError Message:" + ex.Message.ToString() + "\nStack Trace:" + ex.StackTrace.ToString();
				Log.Instance.WriteErrorLog(err, ex);
				//Server.Transfer("~/Error.aspx?m=");
				//Server.ClearError();
				//Response.Redirect("~/Error.aspx");
				//Response.End();
			}
		}

		protected void Session_End(object sender, EventArgs e)
		{
			SBACNEntities objectContext = Session["SBACNEntities"] as SBACNEntities;
			if (objectContext != null)
			{
				objectContext.Dispose();
			}
		}

		protected void Application_End(object sender, EventArgs e)
		{

		}
	}
}